package com.adapters;

import java.util.List;

import com.objects.Recepient;
import com.senditcertified.mail.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class RecepientAdapter extends ArrayAdapter<Recepient> {

	private int currentPosition;
	private OnClickAction action;

	public RecepientAdapter(Context context, List<Recepient> recepients) {
		super(context, R.layout.recepient_tab_item, recepients);
		currentPosition = 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = LayoutInflater.from(getContext()).inflate(
					R.layout.recepient_tab_item, parent, false);
			holder = new ViewHolder();
			holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
			holder.btnRemove = convertView.findViewById(R.id.btn_remove);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (position == currentPosition) {
			convertView.setSelected(true);
		} else {
			convertView.setSelected(false);
		}
		holder.tvName.setSelected(true);
		Recepient recepient = getItem(position);
		if (recepient.getContact().getName() == null
				|| recepient.getContact().getName().length() == 0) {
			holder.tvName.setText(recepient.getContact().getFirstName() + " "
					+ recepient.getContact().getLastName());
		} else {
			holder.tvName.setText(recepient.getContact().getName());
		}
		convertView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				currentPosition = position;
				notifyDataSetChanged();
				if (action != null) {
					action.onItemClick(getItem(position), position);
				}
			}
		});

		holder.btnRemove.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (currentPosition > 0) {
					currentPosition--;
				}
				Recepient recepient = getItem(position);
				remove(getItem(position));
				notifyDataSetChanged();
				if (action != null) {
					action.onRemoveClick(recepient, position);
				}
			}
		});

		return convertView;
	}

	public void setAction(OnClickAction action) {
		this.action = action;
	}

	public void setCurrentPosition(int position) {
		currentPosition = position;
	}

	public int getCurrentPosition() {
		return currentPosition;
	}

	private class ViewHolder {
		private View btnRemove;
		private TextView tvName;
	}

	public interface OnClickAction {
		public void onItemClick(Recepient recepient, int position);

		public void onRemoveClick(Recepient recepient, int position);
	}
}
